/**
 * author: zhou
 * date: 2017.10.18
 * description: 学校控制中心
 * functions: {
 *      save: 保存学校
 *      findAll: 获取全部学校
 *      findOne: 获取学校信息
 *      update: 更新学校
 *      del: 删除学校
 *      disable: 禁用学校
 * }
 * 
 */

const   mongoPromise = require('../../../core/mongo/mongoPromise'),
        utils        = require('../../../utils/utils'),
        School  = require('../../../core/mongo/models/system/schoolModel'),
        User    = require('../../../core/mongo/models/system/userModel');

const schoolController = {
    /**
     * 保存学校
     * 保存成功后自动创建学校管理员用户
     * @param {*} ctx 
     */
    async save(ctx) {
        const { username, schoolName, schoolmaster, province, address, introduction, teacherCount, studentCount } = ctx.request.body.data;
        if (!username) {
            ctx.body = { success: false, message: '学校管理员用户名不能为空', state: 10004 };
            return;
        }
        const school = new School({
            username,
            schoolName: schoolName || '',
            schoolmaster: schoolmaster || '',
            province: province[0] || '',
            city: province[1] || '',
            area: province[2] || '',
            address: address || '',
            introduction: introduction || '',
            count: {
                teacher: teacherCount || 0,
                student: studentCount || 0
            }
        });
        await School.create(school).then(async (doc) => {
            // 生成学校账户
            const user = new User({
                username,
                password: utils.encrpt(utils.encrpt(`${username}_123456`, 'school client'), 'Well students!China future!'),
                name: schoolName,
                schoolId: doc._id,
                type: 2,
                status: 1,
                isSchoolManager: true,
                ip: ctx.ip
            });
            await User.create(user).then((userDoc) => {
                ctx.body = { success: true, data: [], state: 200 };
            },
            (error) => {
                ctx.body = { success: false, message: '保存学校管理员用户失败', state: 10003 };
            });
        },
        (error) => {
            ctx.body = { success: false, message: '保存失败', state: 10003 };
        });
    },
    /**
     * 获取全部学校
     * @param {*} ctx 
     */
    async findAll(ctx) {
        const { page, limit } = ctx.request.body.data;
        if (!page || !limit) {
            ctx.body = { success: false, message: '抱歉,参数有误', state: 10004 };
            return;
        }
        const query = School.find({ status: { $lt: 3 }}).skip((page - 1) * limit).limit(limit);
        const result = await mongoPromise(ctx, query);
        if (result) {
            const countQuery = School.count();
            const countResult = await mongoPromise(ctx, countQuery);
            if (countResult !== undefined) {
                ctx.body = { success: true, data: { data: result, count: countResult }, state: 200 };
            }
        }
    },
    /**
     * 获取学校信息
     * @param {*} ctx 
     */
    async findOne(ctx) {
        const { id } = ctx.request.body.data;
        if (!id) {
            ctx.body = { success: false, message: '学校id不能为空', state: 10004 };
            return;
        }
        const query = School.findById(id);
        const result = await mongoPromise(ctx, query);
        if (result) {
            ctx.body = { success: true, data: result, state: 200 };
        }
    },
    /**
     * 更新学校
     * @param {*} ctx 
     */
    async update(ctx) {
        const { _id, username, schoolName, schoolmaster, province, address, introduction, teacherCount, studentCount } = ctx.request.body.data;
        if (!_id) {
            ctx.body = { success: false, message: '学校id不能为空', state: 10004 };
            return;
        }
        const school = {
            username,
            schoolName: schoolName || '',
            schoolmaster: schoolmaster || '',
            province: province[0] || '',
            city: province[1] || '',
            area: province[2] || '',
            address: address || '',
            introduction: introduction || '',
            count: {
                teacher: teacherCount || 0,
                student: studentCount || 0
            },
            status: 1
        };
        const query = School.update({ _id }, school);
        const result = await mongoPromise(ctx, query);
        if (result) {
            ctx.body = { success: true, data: [], state: 200 };
        }
    },
    /**
     * 删除学校
     * @param {*} ctx 
     */
    async del(ctx) {
        const { id } = ctx.request.body.data;
        if (!id) {
            ctx.body = { success: false, message: '学校id不能为空', state: 10004 };
            return;
        }
        const query = School.update({ _id: id }, { $set: { status: 3 }});
        const result = await mongoPromise(ctx, query);
        if (result) {
            ctx.body = { success: true, data: [], state: 200 };
        }
    },
    /**
     * 禁用学校
     * @param {*} ctx 
     */
    async disable(ctx) {
        const { id, status } = ctx.request.body.data;
        if (!id) {
            ctx.body = { success: false, message: '学校id不能为空', state: 10004 };
            return;
        }
        const query = School.update({ _id: id }, { $set: { status }});
        const result = await mongoPromise(ctx, query);
        if (result) {
            ctx.body = { success: true, data: [], state: 200 };
        }
    }
};

module.exports = schoolController;